import type { AttachmentsProps } from 'ant-design-x-vue'
import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import xUserService from '@/services/user'

interface Error {
  status: number
  message: string
}

interface Staging {
  key: Id
  value: any
}

/**
 * 生成新的key
 */
const geneKey = () => {
  return Math.random().toString().slice(2, 7)
}

/**
 * 全局管理
 *
 * @description 管理非用户与聊天相关全局数据存取功能
 */
export const useGlobalStore = defineStore('global', () => {
  // 当前已上传附件
  const attachKey = ref(geneKey())
  const currentAttachs = ref<AttachmentsProps['items']>([])
  // 当前系统主题
  const systemTheme = ref(xUserService.getInstance().getSystemTheme())

  // 页面级错误
  const pageError = ref<Error>()
  // 暂存数据
  const stagings = ref<Staging[]>([])

  // ----- Functions -----

  // ----- Getters -----

  const isDarkTheme = computed(() => systemTheme.value === 'dark')

  const hasPageError = computed(() => !!pageError.value?.status)

  // ----- Actions -----

  /**
   * 设置暗色主题
   *
   * @param value 是否暗色主题
   */
  const setDarkTheme = (value: boolean) => {
    xUserService.getInstance().setSystemTheme(value ? 'dark' : 'light')
    systemTheme.value = xUserService.getInstance().getSystemTheme()
  }

  /**
   * 获取当前已上传附件
   *
   * @returns
   */
  const getCurrentAttachs = () => {
    const attachs: AttachFile[] = []
    for (const file of currentAttachs.value) {
      attachs.push({
        uid: file.uid + attachKey.value,
        mime: file.type,
        name: file.name,
        url: file.url,
        size: file.size,
      })
    }
    return attachs
  }

  /**
   * 清空当前已上传附件
   *
   * @returns
   */
  const clearCurrentAttachs = () => {
    attachKey.value = geneKey()
    currentAttachs.value = []
  }

  /**
   * 设置页面级错误信息
   *
   * @param error 错误信息
   */
  const setPageError = (error: Error | undefined) => {
    pageError.value = error
  }

  /**
   * 设置暂存数据
   *
   * @param key 键
   * @param value 值
   */
  const setStagingValue = (key: Id, value: any) => {
    stagings.value[key] = value
  }

  /**
   * 读取暂存数据
   *
   * @param key 键
   * @param defaultValue 默认值
   * @returns
   */
  const getStagingValue = (key: Id, defaultValue: any) => {
    return stagings.value[key] ?? defaultValue
  }

  return {
    /** binder: 当前附件列表（双向绑定） */
    bindAttachList: currentAttachs,
    /** getter: 是否暗色主题 */
    isDarkTheme,
    /** getter: 当前是否存在页面级错误 */
    hasPageError,
    /** getter: 读取页面级错误信息 */
    readPageError: readonly(pageError),
    /** action: 获取当前已上传附件 */
    getCurrentAttachs,
    /** action: 清空当前已上传附件 */
    clearCurrentAttachs,
    /** action: 设置暗色主题 */
    setDarkTheme,
    /** action: 设置页面级错误信息 */
    setPageError,
    /** action: 设置暂存数据 */
    setStagingValue,
    /** action: 读取暂存数据 */
    getStagingValue,
  }
})
